﻿package kizzo.datastruct   
{	
	import flash.filters.ColorMatrixFilter;
	import kizzo.datastruct.HeapNode;

	public class Path extends HeapNode
	{	
		private var vertex_array:Array;
		private var edges_array:Array;
		private var weight:Number;		
		
		/** 
		 * Creates a path starting from start_vertex. Inittially the path does not have any edges and its weight is zero.
		 */
		public function Path(start_vertex:Vertex) 
		{	
			this.vertex_array = [start_vertex];
			this.edges_array = [];
			this.weight = 0;			
		}
		
		/*
		 * Returns the sum of the weights of all edges in the path.
		 */
		public function totalWeight():Number
		{
			return this.weight;
		}
		
		/*
		 * Adds an edge to the path. The edge must have as a starting vertex the end vertex of the previous edge, 
		 * otherwise an exception will be thrown.
		 */
		public function add(e:Edge):void
		{
			if (this.edges_array.length == 0)
				this.edges_array.push(e);
			else
			{
				if (this.edges_array[edges_array.length - 1].end_vertex != e.start_vertex)
					throw new Error("Error adding edge to path. Start vertex differs from last edge's end vertex");
				else
					this.edges_array.push(e);
			}
			this.vertex_array.push(e.end_vertex);
			this.weight += e.weight;
		}
		
		/*
		 * Returns the last vertex in the path.
		 */ 
		public function getLastVertex():Vertex
		{
			return (this.vertex_array[this.vertex_array.length-1] as Vertex);
		}
		
		/*
		 * Displays the path in text format using trace().
		 */
		public function tracePath():void
		{
			trace("Path:" + this.edges_array.length);
			for (var i:int = 0; i < this.edges_array.length; i++)
				this.edges_array[i].traceEdge();
			trace("Weight:" + this.weight);
		}
		
		/*
		 * Colours a path in the graphical representation of a graph. There is a default ColorMatrixFilter which can be overrided.
		 */
		public function highlight(color_matrix:ColorMatrixFilter=null):void
		{
			if (color_matrix == null)
				color_matrix = new ColorMatrixFilter([1, 0, 0, 0, 255, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0])
			for (var i:int = 0; i < this.edges_array.length; i++)
				this.edges_array[i].sprite.filters = [color_matrix];
		}
		
		/*
		 * Createas an exact copy of a path.
		 */
		public function clone():Path
		{
			var cloned_path:Path = new Path(null);
			cloned_path.edges_array = this.edges_array.slice();
			cloned_path.vertex_array = this.vertex_array.slice();
			cloned_path.weight = this.weight;
			return cloned_path;
		}
				
		override public function get key():Number 
		{
			return this.weight;
		}		
	}
	
}